<template>
  <div class="img">
    <a-upload-dragger name="file" :multiple="isMultiple" :listType="listType" :action="uploadParams.actionUrl"
      :headers="uploadParams.headers" :data="formKeyData" :fileList="fileList" :beforeUpload="beforeUpload"
      :disabled="disabled" :remove="handleRemove" @change="handleChange" @preview="handlePreview"
      :class="[!isMultiple ? 'imgupload' : '', !isMultiple && picUrl ? 'image-upload-single-over' : '']">
      <div>
        <!-- <img v-if="!isMultiple && picUrl" :src="getAvatarView()" style="width:100%;height:100%" /> -->
        <div class="iconp">
          <!-- <a-icon :type="uploadLoading ? 'loading' : 'plus'" /> -->
          <a-icon style="font-size:40px" type="cloud-upload" />
          <div class="ant-upload-text">{{ text }}</div>
        </div>
      </div>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel()">
        <img alt="example" style="width: 100%" :src="previewImage" v-if="accept == 'image/*'" />
        <video alt="example" style="width: 100%" controls v-if="accept == 'video/*'">
          <source :src="previewImage" type="video/mp4" />
          <source :src="previewImage" type="video/ogg" />
          <source :src="previewImage" type="video/webm" />
          <object :data="previewImage" type="">
            <embed :src="previewImage" type="" />
          </object>
        </video>
      </a-modal>
    </a-upload-dragger>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFileAccessHttpUrl } from '@/api/manage'
import { uploadToken } from '@/api/api'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = path => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'JImageUpload',
  data() {
    return {
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      uploadLoading: false,
      picUrl: false,
      headers: {},
      files: [],
      disabled:false,
      fileList: [],
      previewImage: '',
      previewVisible: false,
      token: '',
      formKeyData: {
        token: '',
        key: '',
        // multipartFileList: [],
        // type: 1,
        // visitStatus: 1,
        // userId: '',
        // userName: '',
      },
      uploadHost: this.uploadParams.uploadHost
    }
  },
  props: {
    listType:{
      type: String,
      required: false,
      default: 'picture-card'
    },
    type:{
      type: String,
      required: false,
      default: ''
    },
    text: {
      type: String,
      required: false,
      default: '将文件拖到此处，或点击上传'
    },
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: 'temp'
    },
    value: {
      type: [String, Array],
      required: false
    },
    // disabled: {
    //   type: Boolean,
    //   required: false,
    //   default: false
    // },
    isMultiple: {
      type: Boolean,
      required: false,
      default: false
    },
    //update-begin-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
    number: {
      type: Number,
      required: false,
      default: 0
    },
    //update-end-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
    uploadParams: {
      type: Object,
      default: null,
      required: false
    },
    // update date：20220905 for:上传视频时，必须使用该属性，接受值：video/*
    accept: {
      type: String,
      required: false,
      default: 'image/*'
    },
    fileSize: {
      type: Number,
      required: false,
      default: 20
    }
  },
  watch: {
    value: {
      handler(val, oldValue) {
        if (val instanceof Array) {
          this.initFileList(val.join(','))
        } else {
          this.initFileList(val)
        }
        if (!val || val.length == 0) {
          this.picUrl = false
        }
      },
      //立刻执行handler
      immediate: true
    },
    number: {
      handler(val, oldValue) {
        if (val != oldValue) {
         this.fileList = []
        } 
      },
      //立刻执行handler
      immediate: true
    }
  },
  created() {
    this.fetchUploadToken()
  },
  computed: {
    jobNumber() {
      return this.$store.getters.userInfo.workNo || ''
    }
  },
  methods: {
    fetchUploadToken() {
      uploadToken().then(res => {
        if (res.code == 0) {
          this.token = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    initFileList(paths) {
      if (!paths || paths.length == 0) {
        this.fileList = []
        return
      }
      this.picUrl = true
      let fileList = []
      let arr = paths.split(',')
      for (var a = 0; a < arr.length; a++) {
        let url = getFileAccessHttpUrl(arr[a])
        fileList.push({
          url: url,
          uid: url,
          name: getFileName(arr[a]),
          status: 'done',
          thumbUrl: this.type == 3 ? url + '?vframe/jpg/offset/1' : url // update date：20220905 for:上传视频时回显第一帧
        })
      }
      this.fileList = fileList
      this.$emit('fileChange', this.fileList)
      // console.log(this.fileList)
    },
    beforeUpload: function (file) {
      console.log(file);
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'|| file.type === 'image/gif' || file.type === 'application/zip' ||file.type === 'video/mp4'
      const isPic = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'|| file.type === 'image/gif'
      const isZip = file.type === 'application/zip' || file.type === 'application/x-zip-compressed'

      const isLt2M = file.size / 1024 / 1024 < this.fileSize
      if (!isLt2M) {
        this.$message.error(`图片/视频请小于${this.fileSize}MB!`)
        return new Promise((resolve, reject) => {
          reject()
        })
      }
      if (!this.type) {
        this.$message.error('请先选择上传类型')
          return new Promise((resolve, reject) => {
            reject()
          })
      }
      if (this.type == 1 && !isPic) {
        this.$message.error('上传格式有误！')
          return new Promise((resolve, reject) => {
            reject()
          })
      }
      if (this.type == 2 && !isZip) {
        this.$message.error('上传格式有误！')
          return new Promise((resolve, reject) => {
            reject()
          })
      }
      if (this.type == 3 && file.type != 'video/mp4') {
        this.$message.error('上传格式有误！')
          return new Promise((resolve, reject) => {
            reject()
          })
      }
      // if (this.accept == 'image/*') {
      //   if (!isJpgOrPng) {
      //     this.$message.error('上传格式有误！')
      //     return new Promise((resolve, reject) => {
      //       reject()
      //     })
      //   }
      // }
      
      new Promise((resolve, reject) => {
        // if (this.accept == 'image/*') {
        //   if (!isJpgOrPng) {
        //     this.$message.error('上传格式有误！')
        //     reject(file)
        //   }
        // }
        if (!isLt2M) {
          this.$message.error(`图片/视频请小于${this.fileSize}MB!`)
          reject(file)
        } else {
          this.files.push(file)
          // this.setState(state => ({
          //   files: [...state.files, file],
          // }));
          const key = new Date().getTime() + '-' + file.name
          if (!this.isMultiple || this.number == 1) {
            // 只上传一张 支持使用key
            this.formKeyData = {
              key: key,
              token: this.token
            }
          } else {
            // 支持批量多张上传
            this.formKeyData = {
              // key: key,   // 非必填项，批量上传时不能使用相同key，会导致614报错；不指定key，七牛默认将文件hash作为文件名保存
              token: this.token

            }
          }
          console.log(this.formKeyData);
          // return isJpgOrPng && isLt2M
          resolve(file)
        }
      })
    },
    handleChange(info) {
      let fileList = []
      if (this.isMultiple) {
        fileList = [...info.fileList]
      } else {
        fileList = info.fileList.length > 0 ? [info.fileList[info.fileList.length - 1]] : []
      }
      if (fileList.length > this.number && this.isMultiple) {
        this.$message.warning('最多上传' + this.number + '张！')
        return false
        // fileList = fileList.slice(-this.number)
      }
      if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      } else if (info.file.status === 'done') {
        let list = fileList.map(file => {
          if (file.response) {
            file.url = this.uploadHost + file.response.key
            // update date：20220905 for:上传视频时回显第一帧
            if (this.type == 3) {
              file.thumbUrl = this.uploadHost + file.response.key + '?vframe/jpg/offset/1'
            }
          }
          return file
        })
        this.fileList = list
        // console.log(this.fileList)
        this.$emit('fileChange', this.fileList)
      }

      // update-date:20220701 for:important!!必须设置fileList，否则只会调用一次并且状态为uploading
      this.fileList = [...fileList]
      // update-date:20220701 for:important!!必须设置fileList，否则只会调用一次并且状态为uploading

      /*
        if (info.file.status === 'done' || info.file.status === 'removed') {
          this.handlePathChange()
        } */
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.$emit('fileChange', this.fileList)
    },
    // 预览
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    getAvatarView() {
      if (this.fileList.length > 0) {
        let url = this.fileList[0].url
        return getFileAccessHttpUrl(url)
      }
    },
    handlePathChange() {
      let uploadFiles = this.fileList
      let path = ''
      if (!uploadFiles || uploadFiles.length == 0) {
        path = ''
      }
      let arr = []
      if (!this.isMultiple && uploadFiles.length > 0) {
        arr.push(uploadFiles[uploadFiles.length - 1].response.message)
      } else {
        for (let a = 0; a < uploadFiles.length; a++) {
          // update-begin-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
          if (uploadFiles[a].status === 'done') {
            arr.push(uploadFiles[a].response.message)
          } else {
            return
          }
          // update-end-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
        }
      }
      if (arr.length > 0) {
        path = arr.join(',')
      }
      this.$emit('change', path)
    },
    handleDelete(file) {
      //如有需要新增 删除逻辑
      console.log(file)
    },
    handleCancel() {
      this.close()
      this.previewVisible = false
    },
    close() { }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style scoped>
/* update--begin--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白
    * https://github.com/zhangdaiscott/jeecg-boot/issues/1810
    * https://github.com/zhangdaiscott/jeecg-boot/issues/1779
    */

/deep/ .imgupload .iconp {
  padding: 20px;
}

/* update--end--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白*/

/deep/ .image-upload-single-over .ant-upload-select {
  /* display: none; */
}
</style>

